﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Xml;

namespace Cheka.WinForm.Sample.Course
{
    [DataContract]
    public sealed class StudyPlan
    {
        #region "member variables"

        private IList<Course> m_courses;

        #endregion

        public StudyPlan() { m_courses = new List<Course>(); }

        [DataMember]
        public IList<Course> Courses
        {
            get { return m_courses; }
            // make "set" private, dicating that this "set" will never be used
            // its only purpose is for deserialization
            private set { m_courses = value; }// add "set" for deserializer
        }

        public void AddCourse(Course acourse)
        {
            m_courses.Add(acourse);
        }

        public void RemoveCourse(Course acourse)
        {
            m_courses.Remove(acourse);
        }

        #region "static serialization methodds"

        private static DataContractSerializer m_serializer;

        static StudyPlan()
        {
            m_serializer = new DataContractSerializer(typeof(StudyPlan));
        }

        public static void Save(string fileName, StudyPlan plan)
        {
            XmlWriterSettings setting = new XmlWriterSettings { Indent = true };
            using (XmlWriter writer = XmlWriter.Create(fileName, setting))
            {
                m_serializer.WriteObject(writer, plan);
            }
        }

        public static StudyPlan Load(string fileName)
        {
            using (XmlReader reader = XmlReader.Create(fileName))
            {
                return (StudyPlan)m_serializer.ReadObject(reader);
            }
        }

        #endregion
    }
}
